﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace Auros.Categorisation.Data
{
    internal class DataHelpers
    {
        /// <summary>
        /// Converts the specified datatable to a collection of category objects.
        /// </summary>
        /// <param name="dataTable">The data table to convert to category objects.</param>
        /// <returns>Collection of category objects.</returns>
        internal static IEnumerable<Category> ConvertToCategory(DataTable dataTable)
        {
            foreach (DataRow item in dataTable.Rows)
            {
                var category = DataHelpers.ConvertToCategory(item);

                if (category == null)
                    continue;

                yield return category;
            }
        }

        /// <summary>
        /// Converts data row to a category object.
        /// </summary>
        /// <param name="dataRow">The data row to convert to a category object.</param>
        /// <returns>A single category.</returns>
        internal static Category ConvertToCategory(DataRow dataRow)
        {
            if (dataRow == null)
                return null;

            Category category = new Category();

            category.ID = (int)dataRow["id"];
            category.Name = dataRow["name"] as string;
            category.Description = dataRow["description"] as string;
            category.ParentID = (int)dataRow["parentId"];
            category.Selectable = (bool)dataRow["selectable"];
            category.Enabled = (bool)dataRow["enabled"];
            category.SortOrder = (int)dataRow["sortOrder"];
            category.HasChildren = (int)dataRow["hasChildren"] == 1;

            return category;
        }
    }
}